package bjut.zrpc.core.optimization.serializer;

import bjut.zrpc.core.optimization.interfaces.Serializer;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/24 12:42
 */
public class HessianSerializer implements Serializer {

    @Override
    public byte[] serialize(Object data) {


        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);
            hessianOutput.writeObject(data);
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public <T> T deSerialize(byte[] bytes, Class<T> cls) {

        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            HessianInput hessianInput = new HessianInput(byteArrayInputStream);
            Object readObject = hessianInput.readObject();
            return cls.cast(readObject);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }
}
